﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using WoodAdmin.Common.Attribute;
using WoodAdmin.Common.Extention;
using WoodAdmin.Common.Helper;
using WoodAdmin.Common.Helper.Log;
using WoodAdmin.Models;
using WoodAdmin.Models.ViewModels;
using WoodAdmin.Services;
using SqlSugar;
using SqlSugar.Extensions;

namespace WoodAdmin.Controllers
{
    public class HomeController : BaseController
    {
        private readonly SysGroupService _groupService;
        private readonly SysUserService _userService;
        private readonly SysUserRoleService _userRoleService;
        private readonly AccessService _accessService;

        public HomeController(SysGroupService groupService, SysUserService userService, SysUserRoleService userRoleService, AccessService accessService)
        {
            _groupService = groupService;
            _userService = userService;
            _userRoleService = userRoleService;
            _accessService = accessService;
        }

        /// <summary>
        /// 后台首页
        /// </summary>
        /// <returns></returns>
        [SkipCheckPermission]
        public IActionResult Index()
        {
            NLogger.Info("成功记录日志！");
            SysUser user = CurrentUser;
            if (user == null)
            {
                return RedirectToAction("Login","Login");
            }
            #region 刷新当前用户权限信息
            var currentUserAuthNode = _accessService.CurrentUserAuthNode(user.ID);
            var currentUserRoles = _userRoleService.CurrentUserRoles(user.ID);

            GlobalHelper.SetCurrentAuthNode(currentUserAuthNode);
            GlobalHelper.SetCurrentUserRole(currentUserRoles);

            IndexViewModel model = new IndexViewModel();
            model.NodeList = currentUserAuthNode;
            model.UserInfo = user;
            model.GroupList = _groupService.Queryable().OrderBy(a=>a.SortNo).ToList();
            #endregion
            return View(model);
        }

        /// <summary>
        /// 获取菜单分组数据
        /// </summary>
        /// <returns></returns>
        [SkipCheckPermission]
        public IActionResult GetGroupJson()
        {
            List<SysNode> nodeList = _accessService.CurrentUserAuthNode(CurrentUser.ID);
            List<SysGroup> newGroupList = new List<SysGroup>();
            List<SysGroup> groupList = _groupService.Queryable();
            foreach (var group in groupList)
            {
                if (nodeList.Count(s => s.GroupID == group.ID && s.NodeLevel == 3 && s.DisplayFlag == 1) == 0)
                {
                    continue;
                }
                newGroupList.Add(group);
            }
            return Json(newGroupList.OrderBy(a=>a.SortNo));
        }

        /// <summary>
        /// 获取菜单数据
        /// </summary>
        /// <returns></returns>
        [SkipCheckPermission]
        public IActionResult GetMenuJson()
        {
            List<GroupMenuModel> groupMenuModel = new List<GroupMenuModel>();

            //所有的节点分组
            List<SysGroup> groups = _groupService.Queryable();
            
            //当前用户的所有权限
            var nodes = _accessService.CurrentUserAuthNode(CurrentUser.ID);

            foreach (var group in groups)
            {
                GroupMenuModel menuModel = new GroupMenuModel();
                menuModel.groupMenuTitle = group.Title.ToString();
                menuModel.groupMenuName = group.Name.ToString();
                menuModel.childList = new List<NodeMenuModel>();
                foreach (var acc in nodes.Where(p => (p.NodeLevel == 2 && p.DisplayFlag == 1)).ToList())
                {
                    if (acc.GroupID == group.ID.ObjToInt())
                    {
                        NodeMenuModel nodeMenu = new NodeMenuModel();
                        nodeMenu.title = acc.Title ?? "";
                        nodeMenu.icon = acc.IcoCss ?? "";
                        nodeMenu.href = acc.Link ?? "";
                        nodeMenu.spread = false;
                        var nodeChildList = nodes.Where(p => (p.NodeLevel == 3 && p.Pid.ObjToInt() == acc.ID && p.DisplayFlag == 1)).ToList();
                        if (nodeChildList.Count > 1)
                        {
                            nodeMenu.children = nodeChildList.Select(p => new NodeMenuModel { title = p.Title, icon = p.IcoCss, href = p.Link, spread = false }).ToList();
                        }
                        else if (nodeChildList.Count == 1)
                        {
                            nodeMenu.href = nodes.Where(p => (p.NodeLevel == 3 && p.Pid.ObjToInt() == acc.ID && p.DisplayFlag == 1)).FirstOrDefault().Link;
                            nodeMenu.children = new List<NodeMenuModel>();
                        }
                        else
                        {
                            nodeMenu.children = new List<NodeMenuModel>();
                        }
                        menuModel.childList.Add(nodeMenu);
                    }
                }
                groupMenuModel.Add(menuModel);
            }
            return Json(groupMenuModel);
        }

        [SkipCheckPermission]
        public IActionResult TestException()
        {
            NLogger.Info("错误日志测试！");
            throw new System.Exception("错误日志测试！");
        }

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        [ResponseCache(Duration = 15, Location = ResponseCacheLocation.None, NoStore = true)]
        [SkipCheckPermission]
        public IActionResult Main()
        {
            return View();
        }

        /// <summary>
        /// 错误页
        /// </summary>
        /// <returns></returns>
        [ResponseCache(Duration = 15, Location = ResponseCacheLocation.None, NoStore = true)]
        [SkipCheckPermission]
        public IActionResult ServerError()
        {
            return View();
        }

        /// <summary>
        /// 404页面
        /// </summary>
        /// <returns></returns>
        [ResponseCache(Duration = 15, Location = ResponseCacheLocation.None, NoStore = true)]
        [SkipCheckPermission]
        public IActionResult NotFoundError()
        {
            return View();
        }

        /// <summary>
        /// 无权限页面
        /// </summary>
        /// <returns></returns>
        [ResponseCache(Duration = 15, Location = ResponseCacheLocation.None, NoStore = true)]
        [SkipCheckPermission]
        public IActionResult PerssionError()
        {
            return View();
        }
    }
}
